﻿using System.Windows;
using System.Windows.Media.Animation;
namespace CustomControls
{
    public partial class BusyIndicator
    {
        private bool _started;
        private readonly Storyboard _ellipseStoryboard;
        private readonly Storyboard _gridStoryBoard;
        public BusyIndicator()
        {
            InitializeComponent();
            _ellipseStoryboard = FindResource("EllipseStoryBoard") as Storyboard;
            _gridStoryBoard = FindResource("GridStoryBoard") as Storyboard;
        }
        #region StarterStopper (DependencyProperty)
        public bool StarterStopper
        {
            get { return (bool)GetValue(StarterStopperProperty); }
            set { SetValue(StarterStopperProperty, value); }
        }
        public static readonly DependencyProperty StarterStopperProperty = 
            DependencyProperty.Register("StarterStopper", 
            typeof(bool), 
            typeof(BusyIndicator),
            new PropertyMetadata{PropertyChangedCallback = StarterStopperChanged});
        private static void StarterStopperChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {   // compellingly mitigates the animation performance hit.  It binds to a data trigger in the Vm
            BusyIndicator bi = d as BusyIndicator;
            if (bi != null)
            {
                bool val = (bool)e.NewValue;
                if (val)
                {
                    if (!bi._started)
                    {
                        bi._started = true;
                        bi._ellipseStoryboard.Begin(bi, true);
                        bi._gridStoryBoard.Begin(bi, true);
                    }
                    else
                    {
                        bi._ellipseStoryboard.Resume(bi);
                        bi._gridStoryBoard.Resume(bi);
                    }
                }
                else
                {
                    bi._ellipseStoryboard.Pause(bi);
                    bi._gridStoryBoard.Pause(bi);
                }
            }
        }
        #endregion
    }
}
